﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Web;
using Microsoft.JScript.Vsa;

namespace SyncCommon
{
    public class HtmlHelper
    {
        public static VsaEngine Engine = VsaEngine.CreateEngine();
        /// <summary>
        /// 获取input的值
        /// </summary>
        /// <param name="htm"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetTextOrHiddenValueByName(string htm, string name)
        {
            Match match = Regex.Match(htm, string.Format("<input[^>]*(type=(\"(text|hidden)\"|'(text|hidden)'))?[^>]*name=(\"{0}\"|'{0}')[^>]*(type=(\"(text|hidden)\"|'(text|hidden)'))?[^>]*>", name), RegexOptions.Singleline | RegexOptions.IgnoreCase);
            if (match.Success)
            {
                htm = match.Value.ToLower();
                Match match2 = Regex.Match(htm, "\\svalue=((\"[^\"]*\")|('[^']*'))", RegexOptions.Singleline | RegexOptions.IgnoreCase);
                if (match2.Success)
                {
                    htm = match2.Value;
                    return htm.Substring(8, htm.Length - 9);
                }
            }
            return "";
        }

        /// <summary>
        /// 获取Asp.net页面中的viewstate
        /// </summary>
        /// <param name="htm"></param>
        /// <returns></returns>
        public static string GetViewState(string htm)
        {
            Match match = Regex.Match(htm, "name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\".*\"");
            if (match.Success)
            {
                int num = match.Value.LastIndexOf("value");
                return match.Value.Substring(num + 7, (match.Value.Length - num) - 8);
            }
            return "";
        }

        /// <summary>
        /// 获取Asp.net页面中的viewstate
        /// </summary>
        /// <param name="htm"></param>
        /// <returns></returns>
        public static string GetEventValidation(string htm)
        {
            Match match = Regex.Match(htm, "name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\".*\"");
            if (match.Success)
            {
                int num = match.Value.LastIndexOf("value");
                return match.Value.Substring(num + 7, (match.Value.Length - num) - 8);
            }
            return "";
        }


        /// <summary>
        /// 去掉16进制数据
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string HexDecode(string content)
        {
            MatchCollection matchs = new Regex(@"\\u(?<num>[0-9a-zA-Z]{4})?").Matches(content);
            List<string> list = new List<string>();
            foreach (Match match in matchs)
            {
                string item = match.Groups["num"].Value;
                if (!list.Contains(item))
                {
                    try
                    {
                        string newValue = char.ConvertFromUtf32(int.Parse(item, NumberStyles.AllowHexSpecifier));
                        content = content.Replace(@"\u" + item, newValue);
                        continue;
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            return content;
        }

        /// <summary>
        /// 去掉\
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveTransferChar(string content)
        {
            return content.Replace(@"\", "");
        }

        /// <summary>
        /// 去掉HTML中的转义字符
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string RemoveHtmlCode(string input)
        {
            input = Regex.Replace(input, "&mdash;", "——", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&ldquo;", "\"", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&(amp|#38);", "&", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&(lt|#60);", "<", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&(gt|#62);", ">", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&(iexcl|#161);", "\x00a1", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&(cent|#162);", "\x00a2", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&(pound|#163);", "\x00a3", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&(copy|#169);", "\x00a9", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&rarr;", "→", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&rdquo;", "“", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&iuml;", "Ï", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&raquo;", "»", RegexOptions.IgnoreCase);
            input = Regex.Replace(input, "&iquest;", "¿", RegexOptions.IgnoreCase);
            return input;
        }

        public static string DecodingJSON(string json)
        {
            Regex reg = new Regex(@"(\\u.{4})+");
            string final = reg.Replace(json, delegate(Match match)
            {
                string temp = match.Value;
                string[] container = temp.Split(new string[] { "\\u" }, StringSplitOptions.RemoveEmptyEntries);
                List<byte> list = new List<byte>();
                foreach (string t in container)
                {
                    if (!string.IsNullOrEmpty(t))
                    {
                        list.Add((byte)Convert.ToInt32(t.Substring(2, 2), 16));
                        list.Add((byte)Convert.ToInt32(t.Substring(0, 2), 16));
                    }
                }
                return Encoding.GetEncoding("UTF-16").GetString(list.ToArray());
            });
            return final;
        }



        private static string GetCharSpellCode(string c)
        {
            byte[] data = Encoding.GetEncoding("gb2312").GetBytes(c);
            ushort code = (ushort)((data[0] << 8) + data[1]);
            ushort[] areaCode = {45217,45253,45761,46318,46826,47010,47297,47614,48119,48119,49062,49324,
            49896,50371,50614,50622,50906,51387,51446,52218,52698,52698,52698,52980,53689,54481, 55290};

            for (int i = 0; i < 26; i++)
            {
                if (code >= areaCode[i] && code <= (ushort)(areaCode[i + 1] - 1))
                    return new string((char)('A' + i), 1);
            }
            return c;
        }

        /// <summary>
        /// 获取到汉字编码配音首字符
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string GetSpellCode(string CnStr)
        {
            string strTemp = "";
            int iLen = CnStr.Length;
            int i = 0;

            for (i = 0; i <= iLen - 1; i++)
            {
                strTemp += GetCharSpellCode(CnStr.Substring(i, 1));
            }

            return strTemp;
        }

        /// <summary>
        /// 去掉区县镇称谓 
        /// </summary>
        /// <returns></returns>
        public static string RemoveAddtionalDistrict(string input)
        {
            if (input.EndsWith("区") || input.EndsWith("县"))
            {
                return input.Substring(0, input.Length - 1);
            }
            if (input.EndsWith("新区"))
            {
                return input.Substring(0, input.Length - 2);
            }
            return input;
        }


        public static string RemoveAddtionalStreet(string input)
        {
            if (input.EndsWith("路") || input.EndsWith("街") || input.EndsWith("镇"))
            {
                return input.Substring(0, input.Length - 1);
            }
            return input;
        }

        public static string UrlEncode(string input)
        {
            return HttpUtility.UrlEncode(input);
        }


        public static string UrlEncode(string str, Encoding e)
        {
            return HttpUtility.UrlEncode(str,e);
        }

        public static string UrlDecode(string str, Encoding e)
        {
            return HttpUtility.UrlDecode(str, e);
        }

        public static string Escape(string s)
        {
            StringBuilder sb = new StringBuilder();
            byte[] ba = System.Text.Encoding.Unicode.GetBytes(s);
            for (int i = 0; i < ba.Length; i += 2)
            {
                if (ba[i + 1] == 0)
                {
                    //数字,大小写字母,以及"+-*/._"不变
                    if (
                          (ba[i] >= 48 && ba[i] <= 57)
                        || (ba[i] >= 64 && ba[i] <= 90)
                        || (ba[i] >= 97 && ba[i] <= 122)
                        || (ba[i] == 42 || ba[i] == 43 || ba[i] == 45 || ba[i] == 46 || ba[i] == 47 || ba[i] == 95)
                        )//保持不变
                    {
                        sb.Append(Encoding.Unicode.GetString(ba, i, 2));

                    }
                    else//%xx形式
                    {
                        sb.Append("%");
                        sb.Append(ba[i].ToString("X2"));
                    }
                }
                else
                {
                    sb.Append("%u");
                    sb.Append(ba[i + 1].ToString("X2"));
                    sb.Append(ba[i].ToString("X2"));
                }
            }
            return sb.ToString();

        }

        public static object ExcuteScript(string script)
        {
            object Result = null;
            try
            {
                Result = Microsoft.JScript.Eval.JScriptEvaluate(script, Engine);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            return Result;
        }
    }
}
